//
//  DianLiangPay.m
//  DianLiangPay
//
//  Created by 涂俊 on 2018/2/7.
//  Copyright © 2018年 wyht. All rights reserved.
//

#import "DianLiangPay.h"
#import "Dian/Dian.h"

#import "OpenSDK_H5ViewController.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_PayManager.h"
#import "OpenSDK_Enum.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_ReqDataGenerator.h"

@interface DianLiangPay () <H5ViewController_Delegate>

@end

@implementation DianLiangPay

{
    NSString *curOrderID;
    NSString *productName;
}

static NSString *APP_CONFIG=@"DianLiangPayConfig";
static NSString *APP_ID=@"AppID";
static NSString *APP_KEY=@"AppKey";
static NSString *APP_NAME=@"AppName";

#pragma mark - OpenSDK_SdkProtrol声明方法
- (void)initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(loginWithData:) name:OPENSDK_EVENT_LOGIN_SUCCESS object:nil className:@"DianLiangPay"];
}

//登录成功后的消息
-(void) loginWithData:(NSNotification*) notification {
    OpenSDK_UserInfo *data = [notification object];
    NSError *error = nil;
    NSDictionary *config = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:APP_CONFIG];
    NSString *aid = [config objectForKey:APP_ID];
    NSString *key = [config objectForKey:APP_KEY];
    DianU(aid, key, data.openSDK_openID, &error);
    if (error) {
        NSLog(@"DiangLiangPay DianU() failed:%@", [error localizedDescription]);
    }
}

#pragma mark - OpenSDK_SdkProtrol声明方法 - 服务器唯一标识
-(NSString *) getServerName {
    return @"DianLiang";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的图标
-(NSString *) getDisplayIcon {
    return @"op_pay_dianliang.png";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 展示的名字
-(NSString *) getDisplayName {
    return @"快捷支付";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台名
-(NSString *) getPlatform {
    return @"DianLiang";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 支付平台版本号
-(NSString *) getPlatformVersion {
    return @"1.0";
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 设置创建OpenSDK订单的额外参数
-(void) beforeCreateOrder:(OpenSDK_PayInfo *) payInfo {
    productName = payInfo.productName;// 获取商品名
}

#pragma mark - OpenSDK_PayProtocol声明方法 - 调起第三方平台支付，传入opensdk订单号
-(void) startPay:(OpenSDK_PayResData *) opensdkOrder {
    curOrderID = [opensdkOrder getOrderID];
    // 服务器返回的callbackUrl
    NSDictionary *extra = [opensdkOrder.content objectForKey:@"extra"];
    NSString *callbackUrl = extra ? [extra objectForKey:@"callback"] : @"";
    NSLog(@"callbackUrl=%@", callbackUrl);
    float amount = [[opensdkOrder getProductAmount] floatValue];
    int intAmout = amount * 100;
    NSError *error = nil;
    
    NSDictionary *config = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:APP_CONFIG];
    NSString *aid = [config objectForKey:APP_ID];
    NSString *key = [config objectForKey:APP_KEY];
    NSString *appName = [config objectForKey:APP_NAME];
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    //调用支付接口，获取支付H5地址
    NSString *payUrl = DianP(aid, key, [NSString stringWithFormat:@"%d", intAmout], productName, [opensdkOrder getUID], [opensdkOrder getOrderID], callbackUrl, appName, bundleId, &error);
    if (error) {
        NSLog(@"DiangLiangPay DianP() failed:%@", [error localizedDescription]);
        [[OpenSDK_PayManager getInstance] callbackPayFail:[error localizedDescription] withOrder:nil];
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        OpenSDK_H5ViewController *h5View=[[[OpenSDK_H5ViewController alloc] init] openWithGetUrl:payUrl jsMethods:@[@"onCancel", @"onSuccess"]];
        h5View.delegate = self;
        h5View.hasCloseBtn = YES;
        UIViewController *root=[OpenSDK_UIUtil getCurrentVC];
        //弹出透明背景
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            h5View.modalPresentationStyle=UIModalPresentationOverCurrentContext;
        }else{
            root.modalPresentationStyle=UIModalPresentationCurrentContext;
        }
        [root presentViewController:h5View animated:false completion:^{
        }];
    });
}

- (void) callbackWithName:(NSString *) name args:(id) obj {
    if ([@"onCancel" isEqualToString:name]) {
        // 支付失败
        [[OpenSDK_PayManager getInstance] callbackPayCancel];
    } else if ([@"onSuccess" isEqualToString:name]) {
        // 支付成功
        NSMutableDictionary *orderDic=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
        [orderDic setObject:[self getPlatform] forKey:OpenSDK_S_PLATFORM];
        [orderDic setObject:[self getPlatformVersion] forKey:OpenSDK_S_PLATFORM_VERSION];
        NSString *orderStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:orderDic];
        [self checkOrderWithData:orderStr orderID:curOrderID httpDelegate:^(OpenSDK_BaseResData *resData) {
            if([resData isOk]) {
                // 回调支付成功
                OpenSDK_PayResData *payInfo=[[OpenSDK_PayResData alloc] initWithDictionary:[resData content]];
                OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
                [[OpenSDK_PayManager getInstance] callbackPaySuccess:nil withOrder:userOrderInfo];
            } else {
                // 回调支付失败
                [[OpenSDK_PayManager getInstance] callbackPayFail:[resData errorMsg] withOrder:nil];
            }
        }];
    }
}

- (void) close {
    NSMutableDictionary *orderDic=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
    [orderDic setObject:[self getPlatform] forKey:OpenSDK_S_PLATFORM];
    [orderDic setObject:[self getPlatformVersion] forKey:OpenSDK_S_PLATFORM_VERSION];
    NSString *orderStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:orderDic];
    [self checkOrderWithData:orderStr orderID:curOrderID httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            // 回调支付成功
            OpenSDK_PayResData *payInfo=[[OpenSDK_PayResData alloc] initWithDictionary:[resData content]];
            OpenSDK_OrderInfo *userOrderInfo=[payInfo toUserOrderInfo];
            [[OpenSDK_PayManager getInstance] callbackPaySuccess:nil withOrder:userOrderInfo];
        } else {
            // 回调支付失败
            [[OpenSDK_PayManager getInstance] callbackPayFail:[resData errorMsg] withOrder:nil];
        }
    }];
}

@end
